package server

import (
	"os/exec"
	"smart-weekly-report/config"
	"smart-weekly-report/models"
	"strings"
	"time"
)

// Git服务结构
type GitService struct {
	RepoPath string
}

func NewGitService(repoPath string) *GitService {
	return &GitService{RepoPath: repoPath}
}

// 同步Git提交记录
func (gs *GitService) SyncCommits() error {
	cmd := exec.Command("git", "log", "--pretty=format:%H|%an|%ad|%s", "--date=short")
	cmd.Dir = gs.RepoPath
	output, err := cmd.Output()
	if err != nil {
		return err
	}

	lines := strings.Split(string(output), "\n")
	for _, line := range lines {
		if line == "" {
			continue
		}

		parts := strings.Split(line, "|")
		if len(parts) < 4 {
			continue
		}

		commitTime, _ := time.Parse("2006-01-02", parts[2])
		week := getWeekNumber(commitTime)

		commit := models.GitCommit{
			Hash:      parts[0],
			Author:    parts[1],
			Message:   parts[3],
			Timestamp: commitTime,
			Week:      week,
		}

		// 保存到数据库
		var existingCommit models.GitCommit
		result := config.Db.Where("hash = ?", commit.Hash).First(&existingCommit)
		if result.Error != nil {
			config.Db.Create(&commit)
		}
	}

	return nil
}

// 获取指定周的提交记录
func (gs *GitService) GetCommitsByWeek(week int) ([]models.GitCommit, error) {
	var commits []models.GitCommit
	result := config.Db.Where("week = ?", week).Find(&commits)
	return commits, result.Error
}

// 工具函数：获取周数
func getWeekNumber(t time.Time) int {
	_, week := t.ISOWeek()
	return week
}
